/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.fast.fast.common.gateway.handler;

import com.alibaba.fastjson.JSON;
import com.fast.fast.common.base.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关全局异常处理器类
 *
 * @author lyf
 * @date 2022/01/01 00:00 周六
 **/
@Slf4j
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable throwable) {
        ServerHttpResponse response = exchange.getResponse();

        if (response.isCommitted()) {
            return Mono.error(throwable);
        }

        // 设置响应头媒体类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        // 设置响应头状态码
        HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;

        if (throwable instanceof ResponseStatusException) {
            httpStatus = ((ResponseStatusException) throwable).getStatus();
        }

        if (throwable.getMessage().contains("Token无效")) {
            httpStatus = HttpStatus.FORBIDDEN;
        }

        response.setStatusCode(httpStatus);
        HttpStatus finalHttpStatus = httpStatus;

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            // 异常信息
            String errorInfo = String.format(
                    "网关异常，请求url：%s，%s",
                    exchange.getRequest().getPath(),
                    throwable.getMessage()
            );
            // 异常状态码
            Integer statusCode = finalHttpStatus.value();
            log.error("{},{}", errorInfo, statusCode);
            try {
                return bufferFactory.wrap(JSON.toJSONBytes(Result.error(errorInfo, statusCode)));
            } catch (Exception e) {
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }

}
